// 导入数据库操作
const { sqlOne, sqlBatch } = require('../db/common')
// 加密工具包bcryptjs
const bcrypt = require('bcryptjs')
// 引入jwt
const jwt = require('jsonwebtoken')
// 引入加密字符串
const config = require('../utils/config')
// 导入工具
const utils = require('../utils/index')


const redisClient = require('../utils/redis-client')
const emailUtils = require('../utils/emailUtils')
const logo = require('../utils/logo')

// 成功响应 onSuccess 失败响应 onError

// 数据库表 t_user 列 id username  password  context role  status  

// 登录函数
exports.login = async (req, res) => {
  const userinfo = req.body
  // 判断用户是否存在
  const sql = 'select * from t_user where username = ?'
  const results = await sqlOne(sql, userinfo.username)
  if (results.length === 0) {
    return res.onError("您输入的用户名不存在，请重新输入！")
  }
  // 用户名ok 验证密码 
  // 1.先将密码加密后 再与数据库对比
  const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
  // 判断密码是否正确
  if (!compareResult) {
    return res.onError("密码错误，登录失败！")
  }
  // 判断账号是否有效
  if (results[0].status === 0) {
    return res.onError("该用户状态异常，有问题请联系管理员！")
  }
  // 2.用username生成token对象，响应回去
  const t_user = { ...results[0], password: '' }
  const tokenStr = jwt.sign(t_user, config.jwtSecretKey, { expiresIn: '24h' })
  res.onSuccess({
    status: 0,
    message: "登录成功！",
    token: 'Bearer ' + tokenStr,
    userInfo: t_user
  })
}
// 验证用户提交的验证码  
async function verifyCaptcha(email, submittedCaptcha) {
  const key = `captcha:${email}`;
  const storedCaptcha = await new Promise((resolve, reject) => {
    client.get(key, (err, reply) => {
      if (err) reject(err);
      resolve(reply);
    });
  });

  // 如果Redis中没有验证码或验证码不匹配，返回false  
  return storedCaptcha === submittedCaptcha;
}
// 假设你已经有了生成验证码和保存验证码到 Redis 的函数  
// 这里我们使用一个模拟的验证码  
function generateCaptcha() {
  // 生成一个随机的验证码  
  return Math.floor(100000 + Math.random() * 900000).toString();
}
// 获取邮箱验证码
exports.emailCode = async (req, res) => {
  const { email } = req.query

  const codeX = await redisClient.get(email)
  if (codeX) {
    return res.onError("已发送过验证码，请注意查收!")
  }

  const sql = 'select * from t_user where email = ?'
  const results = await sqlOne(sql, email)
  if (results.length > 0) {
    return res.onError("该邮箱已注册过账号")
  }
  const code = generateCaptcha()
  // 创建邮件内容  
  const mailOptions = {
    from: '1348984154@qq.com', // 发件人地址  
    to: email, // 收件人地址  
    subject: '潮汕文化习俗网站账号注册-验证码', // 邮件主题  
    html: `<div>
    <h1>您的验证码是: ${code}</h1>
    <div style="width:200px;height:200px"> ${logo} </div>
        </div>`, // 邮件内容  
  };

  // 发送邮件  
  await emailUtils.sendMail(mailOptions);
  await redisClient.set(email, code)
  // code
  res.onSuccess(null, '发送验证码成功')
}

// 注册用户
exports.register = async (req, res) => {
  try {
    // 生成uuid
    const userinfo = { ...req.body }
    console.log(userinfo);
    const code = await redisClient.get(userinfo.email)
    if (code !== userinfo.code) {
      return res.onError("验证码错误!")
    }

    if (userinfo.password !== userinfo.repassword) {
      return res.onError("两次密码不一致,请重试!")
    }
    // 判断用户是否存圠
    const sql = 'select * from t_user where username = ?'
    const results = await sqlOne(sql, userinfo.username)
    if (results.length > 0) {
      return res.onError("该用户名已存在，要不要换一个试试？")
    }
    // 密码加工
    userinfo.password = bcrypt.hashSync(userinfo.password, 10)
    // 插入数据处理 插入 id username password
    const sql2 = 'insert into t_user (username,password,email,createdAt) values (?,?,?,?)'
    const results2 = await sqlOne(sql2, [userinfo.username, userinfo.password, userinfo.email,new Date()])
    if (results2.affectedRows !== 1) {
      return res.onError("注册失败！")
    }
    await redisClient.del(userinfo.email)
    res.onSuccess(null, "注册成功")
  } catch (e) {
    res.onError(e)
  }
}


// 个人信息
exports.getUserInfo = async (req, res) => {
  try {
    let { id } = req.query
    if (!id) {
      id = req.auth.id
    }
    //查询信息
    const sql = `select * from t_user where id = ?`;
    const results = await sqlOne(sql, [id])
    results[0].password = ''
    res.onSuccess(results[0])
  } catch (e) {
    res.onError(e)
  }
}

// 修改用户信息
exports.putUserInfo = async (req, res) => {
  try {
    let { phone, gender, avatar } = req.body

    let id = req.auth.id

    //查询信息
    const sql = `update t_user set ? where id = ?`;
    const results = await sqlOne(sql, [{ phone, gender, avatar }, id])
    res.onSuccess()
  } catch (e) {
    res.onError(e)
  }
}


// 修改密码
exports.resetPwd = async (req, res) => {
  try {
    let { oldPassword, newPassword1, newPassword2 } = req.body

    if (newPassword1 !== newPassword2) {
      return res.onError("输入的两个密码不一致！")
    }

    let id = req.auth.id
    const sql1 = 'select * from t_user where id = ?'
    const results1 = await sqlOne(sql1, [id])
    if (results1.length === 0) {
      return res.onError("账号异常")
    }
    // 对比密码
    // 1.先将密码加密后 再与数据库对比
    const compareResult = bcrypt.compareSync(oldPassword, results1[0].password)
    // 判断密码是否正确
    if (!compareResult) {
      return res.onError("旧密码错误！")
    }

    //查询信息
    const sql = `update t_user set ? where id = ?`;
    const results = await sqlOne(sql, [{ password: newPassword1 }, id])
    res.onSuccess()
  } catch (e) {
    console.log(e);
    res.onError(e)
  }
}
